package Tester;

import java.io.File;

import SFT.MultChi;
import WavFile.WavFile;

public class WAVFileCreator {
	
	/*creates a Wav file at location path, as described by the function mc*/
	 public static void CreateWav(String path, MultChi mc){
		 try
			{
				int sampleRate = 44100;		// Samples per second

				// Calculate the number of frames required for specified duration
				long numFrames = mc.maxVal()+1;

				// Create a wav file with the name specified as the first argument
				WavFile wavFile = WavFile.newWavFile(new File(path), 1, numFrames, 16, sampleRate);

				// Create a buffer of 100 frames
				double[] buffer = new double[100];

				// Initialise a local frame counter
				long frameCounter = 0;

				// Loop until all frames written
				while (frameCounter < numFrames)
				{
					// Determine how many frames to write, up to a maximum of the buffer size
					long remaining = wavFile.getFramesRemaining();
					int toWrite = (remaining > 100) ? 100 : (int) remaining;

					// Fill the buffer, one tone per channel
					for (int s=0 ; s<toWrite ; s++, frameCounter++)
					{
						buffer[s] = mc.apply((int) frameCounter).Re();
					}

					// Write the buffer
					wavFile.writeFrames(buffer, toWrite);
				}

				// Close the wavFile
				wavFile.close();
			}
			catch (Exception e)
			{
				System.err.println(e);
			}
	 }

}
